package com.audaque.springboot.foshanupload.web.webdemo.controller;

import com.audaque.springboot.foshanupload.core.util.ObjectInOutputStreamUtil;
import com.audaque.springboot.foshanupload.log.anno.WebLogAnno;
import com.audaque.springboot.foshanupload.web.webdemo.model.domain.Country;
import com.audaque.springboot.foshanupload.web.webdemo.model.domain.Dog;
import com.audaque.springboot.foshanupload.web.webdemo.model.domain.Person;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigDecimal;
import java.util.Date;

@Slf4j
@RestController
@RequestMapping("objectInOutputStream")
public class ObjectInOutputStreamController {
    @WebLogAnno
    @GetMapping("/toByteArr")
    public byte[] toByteArr() throws Exception {
        Person person = new Person();
        person.setDescribe("");
        person.setId("1");
        person.setSource(new BigDecimal("0"));
        person.setHeight(0.0D);
        person.setCreateTime(new Date());
        person.setBirthDate(new Date());
        person.setPersonCountry(new Country());
       return ObjectInOutputStreamUtil.serializeObjectToByteArr(person);
    }

    @WebLogAnno
    @GetMapping("/parse")
    public Object parse( ) throws Exception {
       return ObjectInOutputStreamUtil.byteArrToSerializeObject(toByteArr());
    }
    @WebLogAnno
    @GetMapping("/toFile")
    public void toFile() throws Exception {
        //序列化后，保存的文件格式，不是存文本，而是按照他的格式来保存
        String filePath = "e:\\a.txt";
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(filePath));
        //序列化数据到 d:\oos.txt
        oos.writeInt(100);// int -> Integer (实现了 Serializable)
        oos.writeBoolean(true);// boolean -> Boolean (实现了 Serializable)
        oos.writeChar('a');// char -> Character (实现了 Serializable)
        oos.writeDouble(9.5);// double -> Double (实现了 Serializable)
        oos.writeUTF("ret");//String
        //保存一个 dog 对象
        oos.writeObject(new Dog("旺财", 10, "中国", "黄色"));
    }

    @WebLogAnno
    @GetMapping("/fromFile")
    public void fromFile() throws Exception {
        // 1.创建流对象
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("e:\\a.txt"));
        // 2.读取， 注意顺序
        System.out.println(ois.readInt());
        System.out.println(ois.readBoolean());
        System.out.println(ois.readChar());
        System.out.println(ois.readDouble());
        System.out.println(ois.readUTF());
        System.out.println(ois.readObject());
        // 3.关闭
        ois.close();

    }


}
